import axios from 'axios'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000, //超时时间
})

//配置请求拦截器,在请求之前的数据处理,比如在请求头添加token,所有的请求都会经过拦截器
instance.interceptors.request.use(
  //config:该参数表示当前请求的配置对象
  (config) => {
    //在请求头统一添加token
    //或者请求之前显示lodding图标(这里只演示这个)
    return config
  },
  (err) => {
    return Promise.reject(err)
  },
)

//配置响应拦截器
instance.interceptors.response.use(
  (response) => {
      const httpStatus = response.status
      if (httpStatus !== 200) {
          console.log('服务器错误')
      }
      let apiStatus = response.data.code
      const mapHandler = new Map()
      mapHandler.set('200', response.data.data)
      return mapHandler.get(apiStatus)
  },
  (err) => {
    return Promise.reject(err)
  },
)

const errorHandler = (data: any) => {
}

//封装请求的api
const api = (method = 'GET', url: string, data = {}) => {
  return instance({
    method,
    url,
    params: method === 'GET' ? data : {},
    data: method === 'POST' || method === 'PUT' ? data : {},
  })
}

export const get = (url: string, data: any) => api('GET', url, data)
export const post = (url: string, data: any) => api('POST', url, data)
export const put = (url: string, data: any) => api('PUT', url, data)
export const remove = (url: string, data: any) => api('DELETE', url, data)
